// pages/address-detail/address-detail.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    username: '',
    tel: ''
  },
  async onSubmit(e) {
    const value = e.detail.value;
    if(this.options.id) {
      await db.collection('mock_address').doc(this.options.id).update({
        data: value
      })
    } else {
      await db.collection('mock_address').add({
        data: value
      })
    }
    wx.showToast({
      title: this.options.id ? '编辑成功' : '添加成功',
    })
    if(getCurrentPages().length>1) {
      wx.navigateBack(1)
    } else {
      wx.redirectTo({
        url: '/pages/address/address',
      })
    }
  },


  onLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const {latitude,longitude} = res;
        wx.chooseLocation({
          latitude,
          longitude,
          success: (res) => {
            console.log(res)
            this.setData({
              address: res.address
            })
            
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(!options.id) return
    db.collection('mock_address').doc(options.id).get().then(res => {
      console.log(res)
      this.setData({
        address: res.data.address,
        username: res.data.username,
        tel: res.data.tel,
      })
    })
  },
})